package com.yan.ems.service;

import com.mathworks.engine.MatlabEngine;
import com.yan.ems.exception.ForecastException;
import com.yan.ems.pojo.vo.OptimizationResponse;
import com.yan.ems.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
@Service
public class OptimizationService {
	public Result<OptimizationResponse> optimize(MultipartFile csvFile, String algorithm, int populationSize, int generations) throws Exception {
		log.info("------start saveCsv--------------");
		saveCsvFile(csvFile);
		log.info("------end saveCsv--------------");
		log.info("------start optimize--------------");
//		runMatlab();
		log.info("------end optimize--------------");

		System.out.println(algorithm + " " + populationSize + " " + generations);
		String path1 = "matlab/optimization/result/my_plot.svg";
		String path2 = "matlab/optimization/result/output_plot.svg";

		log.info("------read svgFile-----------");
		String res1 = Files.readString(Path.of(path1));
//		System.out.println(res1);
		String res2 = Files.readString(Path.of(path2));
		log.info("------end svgFile-----------");
		return Result.success(new OptimizationResponse(res1, res2));
	}

	private void runMatlab() throws Exception {
		String command = "run('matlab/optimization/main.m')";
		MatlabEngine engine = MatlabEngine.startMatlab();
		System.out.println("matlab start succeed");
		engine.eval(command);
		engine.eval("disp('Script execution completed.')");
		engine.close();
		System.out.println("matlab succeed");
	}

	private void saveCsvFile(MultipartFile csvFile) throws Exception {
		String fileName = csvFile.getOriginalFilename();
		String path = System.getProperty("user.dir") + File.separator + "matlab" + File.separator + "optimization" + File.separator;
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		path = file.getPath() + File.separator + fileName;
		try {
			csvFile.transferTo(new File(path));
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new ForecastException();
		}
	}
}
